/*
 * 文件名：RoleServiceImpl.java
 * 版权：Copyright by will_awoke
 * 描述：
 * 修改人：will_awoke
 * 修改时间：2014-8-19
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.qbgs.rbac.service.impl;


import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.qbgs.base.BaseResult;
import com.qbgs.base.Page;
import com.qbgs.base.TreeEntity;
import com.qbgs.constant.GlobalConstant;
import com.qbgs.rbac.dao.MenuDao;
import com.qbgs.rbac.dao.RoleDao;
import com.qbgs.rbac.dao.UserDao;
import com.qbgs.rbac.service.RoleService;


/**
 * 
 * @author will_awoke
 * @version 2014-8-19
 * @see RoleServiceImpl
 * @since
 */
@Service(value = "roleService")
public class RoleServiceImpl implements RoleService
{

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private MenuDao menuDao;

    @Override
    public BaseResult queryRolePage(int currentPage, int numPerPage, String roleName)
    {
        Page page = roleDao.queryRolePage(currentPage, numPerPage, roleName);

        // 将easyui分页有关属性、页面操作提示语 存入baseResult
        BaseResult result = new BaseResult(page.getTotal(), page.getRows());
        if (page.getTotal() == 0)
        {
            // 未查询到记录时，添加相应提示语
            result.setSuccess(false);
            result.setOpMsg(GlobalConstant.QUERRY_FAILED);
        }
        return result;
    }

    @Override
    public List<TreeEntity> ztreeAllRoles()
    {
        List<TreeEntity> result = new LinkedList<TreeEntity>();
        List<Map<String, Object>> roles = roleDao.queryAllRoles();
        TreeEntity ztree = null;
        for (Map<String, Object> role : roles)
        {
            ztree = new TreeEntity();
            ztree.setId(String.valueOf(role.get("ROLE_ID")));
            ztree.setName(String.valueOf(role.get("ROLE_NAME")));
            result.add(ztree);
        }
        return result;
    }

    @Override
    public List<TreeEntity> ztreeEditRoles(String userId)
    {
        List<TreeEntity> result = new LinkedList<TreeEntity>();
        List<Map<String, Object>> roles = roleDao.queryAllRoles();
        List<String> roleIdsOfUser = userDao.queryRoleIdsByUserId(userId);
        TreeEntity ztree = null;
        for (Map<String, Object> role : roles)
        {
            String role_id = String.valueOf(role.get("ROLE_ID"));
            ztree = new TreeEntity();
            ztree.setId(role_id);
            ztree.setName(String.valueOf(role.get("ROLE_NAME")));
            //判断当前role是否在该用户所绑定角色id集合内，如果是，则勾选复选框
            if (roleIdsOfUser.contains(role_id))
            {
                ztree.setChecked(true);
            }
            result.add(ztree);
        }
        return result;
    }

    //事务控制
    @Override
    @Transactional
    public boolean addRoleOfMenu(String roleName, String remarks, String menuId)
    {
        //1. 获得新增角色的主键
        String roleId = String.valueOf(roleDao.addRole(roleName, remarks));
        if (StringUtils.isEmpty(roleId))
        {
            return false;
        }
        //2. 插入角色菜单关联
        for (String menu : StringUtils.split(menuId, ","))
        {
            roleDao.addRoleMenu(roleId, menu);
        }
        return true;
    }

    @Override
    public String queryMenuIdsOfRole(String roleId)
    {
        //查询角色所绑定菜单id集合
        List<String> menuIds = roleDao.queryMenuIdsByRoleId(roleId);
        StringBuilder temp = new StringBuilder("");
        for (String menuId : menuIds)
        {
            temp.append(menuId).append(",");
        }
        //截取掉最后一个逗号
        int length = temp.length();
        if (length > 0)
        {
            return temp.substring(0, length - 1);
        }
        return "";
    }

    @Override
    public String queryMenuNamesOfRole(String roleId)
    {
        //查询角色所绑定菜单id集合
        List<String> menuIds = roleDao.queryMenuIdsByRoleId(roleId);
        StringBuilder menuNames = new StringBuilder("");
        for (String menuId : menuIds)
        {
            List<Map<String, Object>> map = menuDao.queryMenuById(menuId);
            //确保菜单id对应的菜单存在
            if (!CollectionUtils.isEmpty(map))
            {
                menuNames.append(String.valueOf(map.get(0).get("MENU_BAR"))).append(",");
            }
        }
        //截取掉最后一个逗号
        int length = menuNames.length();
        if (length > 0)
        {
            return menuNames.substring(0, length - 1);
        }
        return "";
    }

    //事务控制
    @Override
    @Transactional
    public boolean deleteRole(String roleId)
    {
        //1.删除角色菜单绑定关系
        roleDao.deleteMenusOfRole(roleId);

        //2.删除角色
        return roleDao.deleteRole(roleId) > 0;
    }

    @Override
    public boolean isRoleRefUser(String roleId)
    {
        return roleDao.queryRoleRefUser(roleId) > 0;
    }

    //事务控制
    @Override
    @Transactional
    public boolean updateRoleOfMenu(String roleId, String roleName, String remarks, String menuId)
    {
        //1. 修改角色的信息
        roleDao.updateRole(roleId, roleName, remarks);

        //2. 删除角色现有的菜单绑定关系
        roleDao.deleteMenusOfRole(roleId);

        //3. 插入新的角色菜单关联
        for (String menu : StringUtils.split(menuId, ","))
        {
            roleDao.addRoleMenu(roleId, menu);
        }
        return true;
    }

}
